package org.jeecg.modules.golf.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.golf.question.entity.QuestionType;
import org.jeecg.modules.golf.question.mapper.QuestionTypeMapper;
import org.jeecg.modules.golf.question.service.IQuestionTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 问题分类
 * @Author: jeecg-boot
 * @Date:   2020-11-10
 * @Version: V1.0
 */
@Service
public class QuestionTypeServiceImpl extends ServiceImpl<QuestionTypeMapper, QuestionType> implements IQuestionTypeService {

	@Override
    @Transactional(rollbackFor = Exception.class)
	public void addQuestionType(QuestionType questionType) {
        List<String> parentNodeList = new ArrayList<>();

		if(oConvertUtils.isEmpty(questionType.getParentId())){
			questionType.setParentId(IQuestionTypeService.ROOT_PID_VALUE);
			questionType.setTreePath(IQuestionTypeService.ROOT_PID_VALUE);
		}else{
		   // parentNodeList.add(questionType.getParentId());
			//如果当前节点父ID不为空 则设置父节点的hasChildren 为1
			QuestionType parent = baseMapper.selectById(questionType.getParentId());


			if(parent!=null && !"1".equals(parent.getHasChild())){
				parent.setHasChild("1");
				baseMapper.updateById(parent);
			}
			do{
			    if(IQuestionTypeService.ROOT_PID_VALUE.equals(parent.getParentId())){
			       parentNodeList.add(parent.getId());
			       parent = null;
                }else{
                    parentNodeList.add(parent.getId());
                    parent = baseMapper.selectById(parent.getParentId());                                                                                                                                                                                             parent = baseMapper.selectById(parent.getParentId());

                }
            }while(parent != null);



		}
		baseMapper.insert(questionType);
        parentNodeList.add(0,questionType.getId());
        StringBuilder treeNodeStr = new StringBuilder();
        for(int i= parentNodeList.size() -1;i>=0;i--){
            treeNodeStr.append(parentNodeList.get(i));
            if (i > 0) {
                treeNodeStr.append(",");
            }
        }
        questionType.setTreePath(treeNodeStr.toString());
        baseMapper.updateById(questionType);

	}

	@Override
	public void updateQuestionType(QuestionType questionType) {
		QuestionType entity = this.getById(questionType.getId());
		if(entity==null) {
			throw new JeecgBootException("未找到对应实体");
		}
		String old_pid = entity.getParentId();
		String new_pid = questionType.getParentId();
		if(!old_pid.equals(new_pid)) {
			updateOldParentNode(old_pid);
			if(oConvertUtils.isEmpty(new_pid)){
				questionType.setParentId(IQuestionTypeService.ROOT_PID_VALUE);
			}
			if(!IQuestionTypeService.ROOT_PID_VALUE.equals(questionType.getParentId())) {
				baseMapper.updateTreeNodeStatus(questionType.getParentId(), IQuestionTypeService.HASCHILD);
			}
		}
		baseMapper.updateById(questionType);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteQuestionType(String id) throws JeecgBootException {
		//查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    QuestionType questionType = this.getById(idVal);
                    String pidVal = questionType.getParentId();
                    //查询此节点上一级是否还有其他子节点
                    List<QuestionType> dataList = baseMapper.selectList(new QueryWrapper<QuestionType>().eq("parent_id", pidVal).notIn("id",Arrays.asList(idArr)));
                    if((dataList == null || dataList.size()==0) && !Arrays.asList(idArr).contains(pidVal)
                            && !sb.toString().contains(pidVal)){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            QuestionType questionType = this.getById(id);
            if(questionType==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(questionType.getParentId());
            baseMapper.deleteById(id);
        }
	}

	@Override
    public List<QuestionType> queryTreeListNoPage(QueryWrapper<QuestionType> queryWrapper) {
        List<QuestionType> dataList = baseMapper.selectList(queryWrapper);
        List<QuestionType> mapList = new ArrayList<>();
        for(QuestionType data : dataList){
            String pidVal = data.getParentId();
            //递归查询子节点的根节点
            if(pidVal != null && !"0".equals(pidVal)){
                QuestionType rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<Map<String, String>> queryTypeByUserId(String userid) {
        return getBaseMapper().queryTypeByUserId(userid);
    }

    /**
	 * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
	 * @param pid
	 */
	private void updateOldParentNode(String pid) {
		if(!IQuestionTypeService.ROOT_PID_VALUE.equals(pid)) {
			Integer count = baseMapper.selectCount(new QueryWrapper<QuestionType>().eq("parent_id", pid));
			if(count==null || count<=1) {
				baseMapper.updateTreeNodeStatus(pid, IQuestionTypeService.NOCHILD);
			}
		}
	}

	/**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private QuestionType getTreeRoot(String pidVal){
        QuestionType data =  baseMapper.selectById(pidVal);
        if(data != null && !"0".equals(data.getParentId())){
            return this.getTreeRoot(data.getParentId());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<QuestionType> dataList = baseMapper.selectList(new QueryWrapper<QuestionType>().eq("parent_id", pidVal));
        if(dataList != null && dataList.size()>0){
            for(QuestionType tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }

}
